//
//  ChatViewController.m
//  YSSmartHome
//
//  Created by yanghao on 2017/3/20.
//  Copyright © 2017年 yahaong. All rights reserved.
//

#import "ChatViewController.h"
#import "YSCommon.h"
#import "ChatMessageCell.h"
#import "ZTMessage.h"
#import "IMMessageModel.h"
#import "IMConfig.h"
#import "IQKeyboardManager.h"
#import "MQTTSessionManager.h"
#import "DataBaseManager.h"

static NSString* const ZTChatViewCellIdentfier = @"ZTChatViewCellIdentfier";
@interface ChatViewController ()
<
DataManagerRefreshDelegate
>
@property (nullable, nonatomic, strong) IMMessageModel* messageModel;

@end

@implementation ChatViewController


#pragma mark - life cycle

- (void)dealloc{
    NSLog(@"ChatViewController dealloc");
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kBgColor;
    self.messageModel = [[IMMessageModel alloc]init];
    [kDataManager addIMMessageRefreshDelegate:self];
    [self loadMessage];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [kDataManager removeIMMessageRefreshDelegate:self];
    [kDataManager imMessageCallBack];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [[IQKeyboardManager sharedManager] setEnable:NO];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnable:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)didPressSendButton:(UIButton *)button
           withMessageText:(NSString *)text
                  senderId:(NSString *)senderId
         senderDisplayName:(NSString *)senderDisplayName
                      date:(NSDate *)date {
    self.messageText = text;
    self.messageDate = date;
    [self sendMessageWithText:text senderId:senderId senderDisplayName:senderDisplayName date:date];
}

- (void)didPressAccessoryButton:(UIButton *)sender {

}

#pragma mark - DataManagerRefreshDelegate

- (void)imMessageRefresh:(DataManager *)manager {
    [self loadMessage];
}

#pragma mark - JSQMessagesCollectionViewDataSource
- (NSString *)senderDisplayName {
    return self.user.mobile;
}

- (NSString *)senderId
{
    return kMQTTSessionManager.currentUser.m_strTel;
}

- (id<JSQMessageData>)collectionView:(JSQMessagesCollectionView *)collectionView messageDataForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [self.messageModel.messages objectAtIndex:indexPath.item];
}
- (void)collectionView:(JSQMessagesCollectionView *)collectionView didDeleteMessageAtIndexPath:(NSIndexPath *)indexPath {
    
}
- (id<JSQMessageBubbleImageDataSource>)collectionView:(JSQMessagesCollectionView *)collectionView messageBubbleImageDataForItemAtIndexPath:(NSIndexPath *)indexPath {
    JSQMessage *message = [self.messageModel.messages objectAtIndex:indexPath.item];
    
    if ([message.senderId isEqualToString:self.senderId]) {
        return self.messageModel.outgoingBubbleImageData;
    }
    
    return self.messageModel.incomingBubbleImageData;
}
- (id<JSQMessageAvatarImageDataSource>)collectionView:(JSQMessagesCollectionView *)collectionView avatarImageDataForItemAtIndexPath:(NSIndexPath *)indexPath {
    JSQMessage *message = [self.messageModel.messages objectAtIndex:indexPath.item];
    if ([message.senderId isEqualToString:kMQTTSessionManager.currentUser.m_strTel]) {
        return [self.messageModel.avatars objectForKey:ZTAvatarIdMe];
    } else {
         return [self.messageModel.avatars objectForKey:ZTAvatarIdAdmin];
    }
}

- (NSAttributedString *)collectionView:(JSQMessagesCollectionView *)collectionView attributedTextForCellTopLabelAtIndexPath:(NSIndexPath *)indexPath
{
    JSQMessage *message = [self.messageModel.messages objectAtIndex:indexPath.item];
    return [[JSQMessagesTimestampFormatter sharedFormatter] attributedTimestampForDate:message.date];
}


#pragma mark - UICollectionView DataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.messageModel.messages count];
}

- (UICollectionViewCell *)collectionView:(JSQMessagesCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    JSQMessagesCollectionViewCell *cell = (JSQMessagesCollectionViewCell *)[super collectionView:collectionView cellForItemAtIndexPath:indexPath];
    JSQMessage *msg = [self.messageModel.messages objectAtIndex:indexPath.item];
    
    if (!msg.isMediaMessage) {
        
        if ([msg.senderId isEqualToString:self.senderId]) {
            cell.textView.textColor = [UIColor blackColor];
        }
        else {
            cell.textView.textColor = [UIColor darkGrayColor];
        }
        
        cell.textView.linkTextAttributes = @{ NSForegroundColorAttributeName : cell.textView.textColor,
                                              NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle | NSUnderlinePatternSolid) };
    }
    
    return cell;
}


#pragma mark - Adjusting cell label heights

- (CGFloat)collectionView:(JSQMessagesCollectionView *)collectionView
                   layout:(JSQMessagesCollectionViewFlowLayout *)collectionViewLayout heightForCellTopLabelAtIndexPath:(NSIndexPath *)indexPath
{
    return kJSQMessagesCollectionViewCellLabelHeightDefault;
}

- (CGFloat)collectionView:(JSQMessagesCollectionView *)collectionView
                   layout:(JSQMessagesCollectionViewFlowLayout *)collectionViewLayout heightForMessageBubbleTopLabelAtIndexPath:(NSIndexPath *)indexPath
{
    JSQMessage *currentMessage = [self.messageModel.messages objectAtIndex:indexPath.item];
    if ([[currentMessage senderId] isEqualToString:self.senderId]) {
        return 0.0f;
    }
    
    return kJSQMessagesCollectionViewCellLabelHeightDefault;
}

#pragma mark - private method
- (void)sendMessageWithText:(NSString*)text
                   senderId:(NSString *)senderId
          senderDisplayName:(NSString *)senderDisplayName
                       date:(NSDate *)date
{
    JSQMessage *message = [[JSQMessage alloc] initWithSenderId:senderId
                                             senderDisplayName:senderDisplayName
                                                          date:date
                                                          text:text];
    [self.messageModel.messages addObject:message];
    [self finishSendingMessageAnimated:YES];
    [kDataBaseManager storeIMMessagefromApsn:kZTCloudGatewayApsn fromLuid:kMQTTSessionManager.currentUser.luid toApsn:kZTCloudGatewayApsn toLuid:[XAI mobileToLuid:self.user.mobile] type:0 isRead:1 timestamp: [date  timeIntervalSince1970] data:[[XAITLV alloc]initWithType:XAI_DATA_TYPE_ASCII_TEXT bytes:(void*)[text UTF8String]  length:[text dataUsingEncoding:NSUTF8StringEncoding].length]];
    [kMQTTSessionManager.xai sendIMToApsn:0x01 toLuid:[XAI mobileToLuid:self.user.mobile] dataType:XAI_DATA_TYPE_ASCII_TEXT bytes:(void*)[text UTF8String] length:[text dataUsingEncoding:NSUTF8StringEncoding].length];
    [kDataManager imMessageCallBack];
}


- (void)loadMessage
{
    [kDataBaseManager modifyUnReadMessageWithApsn:kZTCloudGatewayApsn luid:[XAI mobileToLuid:self.user.mobile]];
    __weak typeof(self) wself = self;
    [kDataBaseManager loadIMMessageWithApsn:kZTCloudGatewayApsn luid:[XAI mobileToLuid:self.user.mobile] complete:^(NSArray *array) {
        __strong typeof(wself)sself = wself;
        if (!sself) {
            return ;
        }
         __weak typeof(self) wself = sself;
        dispatch_async(dispatch_get_main_queue(), ^{
            __strong typeof(wself)sself = wself;
            if (!sself) {
                return ;
            }
            sself.messageModel.messages = [array mutableCopy];
            [sself.collectionView reloadData];
            [sself scrollToBottomAnimated:YES];
        });
    }];
}
#pragma mark - getters and setters

- (void)setUser:(Friend *)user
{
    _user = user;
    self.navigationItem.title = user.mobile;
}

@end
